<script lang="tsx">
import { defineComponent, ref, onMounted, onUnmounted, watch, type PropType } from 'vue';
import { getImgUrl } from '#/utils/getImgUrl';
import { bufferToBase64 } from '../utils/bufferToBase64';

interface DraggableItem {
  id: string;
  x: number;
  y: number;
  content: string;
  width?: number;
  height?: number;
}

export default defineComponent({
  name: 'DraggableArea',
  props: {
    bgUrl: {
      type: String,
      default: ''
    },
    blocks: {
      type: Array as PropType<DraggableItem[]>,
      default: () => []
    },
    width: {
      type: [String, Number],
      default: '100%'
    },
    height: {
      type: [String, Number],
      default: 'auto'
    },
    showBoundary: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:blocks', 'item-moved'],
  setup(props, { emit }) {
    const containerRef = ref<HTMLDivElement>();
    const draggedItem = ref<DraggableItem | null>(null);
    const dragOffset = ref({ x: 0, y: 0 });
    const isDragging = ref(false);
    const backgroundImage = ref<HTMLImageElement | null>(null);
    const imgLoading = ref(false);
    const imgLoaded = ref(false);

        // 开始拖拽
    const handleMouseDown = (event: MouseEvent, item: DraggableItem) => {
      if (!containerRef.value) return;
      
      const rect = containerRef.value.getBoundingClientRect();
      const offsetX = event.clientX - rect.left - item.x;
      const offsetY = event.clientY - rect.top - item.y;
      
      draggedItem.value = item;
      dragOffset.value = { x: offsetX, y: offsetY };
      isDragging.value = true;
      
      // 输出容器信息用于调试
      console.log('容器尺寸:', {
        width: containerRef.value.clientWidth,
        height: containerRef.value.clientHeight,
        rect: rect
      });
      
      event.preventDefault();
    };

        // 拖拽中
    const handleMouseMove = (event: MouseEvent) => {
      if (!isDragging.value || !draggedItem.value || !containerRef.value) return;
      
      const rect = containerRef.value.getBoundingClientRect();
      const newX = event.clientX - rect.left - dragOffset.value.x;
      const newY = event.clientY - rect.top - dragOffset.value.y;
      
      // 获取容器的实际尺寸
      const containerWidth = containerRef.value.clientWidth;
      const containerHeight = containerRef.value.clientHeight;
      
      // 获取拖拽元素的尺寸
      const itemWidth = draggedItem.value.width || 100;
      const itemHeight = draggedItem.value.height || 50;
      
      // 限制在容器范围内，确保元素完全在容器内
      const clampedX = Math.max(0, Math.min(newX, containerWidth - itemWidth));
      const clampedY = Math.max(0, Math.min(newY, containerHeight - itemHeight));
      
      // 更新拖拽中的项目位置
      draggedItem.value.x = clampedX;
      draggedItem.value.y = clampedY;
    };

    // 结束拖拽
    const handleMouseUp = () => {
      if (isDragging.value && draggedItem.value) {
        // 触发更新事件
        const updatedItems = props.blocks.map(item =>
          item.id === draggedItem.value?.id
            ? { ...item, x: draggedItem.value.x, y: draggedItem.value.y }
            : item
        );

        emit('update:blocks', updatedItems);
        emit('item-moved', draggedItem.value);

        draggedItem.value = null;
        isDragging.value = false;
      }
    };

    async function loadImage(url: string) {
      try {
        imgLoading.value = true
        const src = await getImgUrl(url) as any
        const base64Content = bufferToBase64(src)
        const img = new Image()
        img.src = base64Content
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          backgroundImage.value = img
          imgLoaded.value = true
          imgLoading.value = false
        };
        img.onerror = () => {
          imgLoaded.value = false
          imgLoading.value = false
        };
      } catch (error) {
        imgLoading.value = false
      }
    }

    // 监听背景图片变化
    watch(() => props.bgUrl, (newUrl) => {
      if (newUrl) {
        loadImage(newUrl);
      }
    });

    // 添加全局事件监听
    onMounted(() => {
      if (props.bgUrl) {
        loadImage(props.bgUrl);
      }
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    });

    onUnmounted(() => {

      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    });

        return () => (
      <div class="draggable-area">
        <div 
          ref={containerRef}
          class="draggable-container"
          style={{
            width: props.width,
            height: props.height,
            backgroundImage: backgroundImage.value ? `url(${backgroundImage.value.src})` : 'none',
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat'
          }}
        >
          {imgLoading.value && (
            <div class="loading-overlay">
              <div class="loading-spinner">加载中...</div>
            </div>
          )}
          
          {/* 显示拖拽边界 */}
          {props.showBoundary && (
            <div class="boundary-indicator">
              <div class="boundary-text">拖拽范围</div>
            </div>
          )}
          
          {props.blocks.map((item) => (
            <div
              key={item.id}
              class={`draggable-item ${isDragging.value && draggedItem.value?.id === item.id ? 'dragging' : ''}`}
              style={{
                left: `${item.x}px`,
                top: `${item.y}px`,
                width: item.width ? `${item.width}px` : 'auto',
                height: item.height ? `${item.height}px` : 'auto'
              }}
              onMousedown={(e) => handleMouseDown(e, item)}
            >
              {item.content}
            </div>
          ))}
        </div>
      </div>
    );
  }
});
</script>

<style scoped>
.draggable-area {
  display: flex;
  justify-content: center;
  align-items: center;
}

.draggable-container {
  position: relative;
  background-color: #f8f9fa;
  overflow: hidden;
}

.draggable-item {
  position: absolute;
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border-radius: 6px;
  cursor: move;
  user-select: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.2s ease;
}

.draggable-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.draggable-item.dragging {
  z-index: 1000;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  opacity: 0.8;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.loading-spinner {
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 8px;
  font-size: 14px;
}

.boundary-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 2px dashed #007bff;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 12px;
  color: #007bff;
  pointer-events: none;
  z-index: 50;
}

.boundary-text {
  font-weight: bold;
}
</style>
